// 生词学习应用主逻辑

class VocabularyApp {
  constructor() {
    // 初始化属性
    this.words = [];
    this.currentIndex = 0;
    this.currentEditId = null; // 用于跟踪当前编辑的词汇ID

    
    
    // 默认生词库(全部生词)
    this.defaultVocabulary = [
      '独', '晶', '娃', '姑', '姨', '叔', '伯', '夏', '江', '浪', '春', '秋', '实', '冬', '寒', '冻', 
      '娘', '母', '亲', '爱', '北', '方', '雪', '南', '芽', '惊', '百', '千', '如', '色', '夜', '草', 
      '都', '未', '见', '晚', '作', '芳', '万', '开', '答', '双', '接', '苹', '果', '巧', '克', '力', 
      '蛋', '糕', '客', '张', '嘴', '巴', '连', '位', '东', '西', '肚', '破', '奔', '跑', '休', '息', 
      '回', '答', '游', '戏', '温', '暖', '身', '体', '树', '叶', '害', '虫', '天', '空', '夜', '晚', 
      '礼', '物', '打', '开', '新', '年', '草', '芽', '白', '雪', '梨', '花', '树', '林', '河', '马', 
      '朋', '友', '蚂', '蚁'
    ];

    this.v20251020 = ["知","道","肯","定","脏","爬","舌","瓶","倒","抓","兔子","肯定","巫婆","忘记"];

    this.v20251021 = ['盼', '粉', '荷', '悄', '莲', '捉', '脚', '步', '霞', '近'];
 
    this.v202510zh = ['脖','围','巾','青','灰','白','黑','彩','虹','丽',
                      '屋','毛','线','羊','金','黄','消','息','忙','织',
                      '年','烧','肉','熟','油','汁','拉','推','净','再',
                      '知','道','肯','定','爬','脏','抓','倒','瓶','舍',
                      '盼','粉','荷','悄','莲','捉','脚','步','霞','近',
                      '桃','杏','李','软','田','野','散','切','几','满',
                      '仙','女','美','丽','脖','子','结','束',
                      '草','地','动','物','漂','亮','彩','虹',
                      '好','吃','干','净','耳','朵','椅','子',
                      '兔','子','肯','定','巫','婆','忘','记',
                      '田','野','睡','觉','池','塘','伙','伴',
                      '脚','步','出','来','野','花','眼','睛'];

    this.v20251103 = ['刚', '猴', '骑', '屁', '股', '现', '等', '久', '拍', '怪'];
    // 重构结构
    this.vocabularyMap = new Map();
    this.vocabularyMap.set('all', this.defaultVocabulary);
    this.vocabularyMap.set('20251020', this.v20251020);
    this.vocabularyMap.set('20251021', this.v20251021);
    this.vocabularyMap.set('202510hz', this.v202510zh);
    this.vocabularyMap.set('20251103', this.v20251103);

    //'奔跑','休息','回答','游戏','温暖','身体','树叶','害虫','天空','夜晚','礼物','打开','新年','草芽','白雪','梨花','树林','河马','朋友','蚂蚁'
    // this.defaultVocabulary = [
    //   '独', '晶', '娃', '姑', '姨', '叔', '伯', '夏', '江', '浪', '春', '秋', '实', '冬', '寒', '冻', 
    //   '娘', '母', '亲', '爱', '北', '方', '雪', '南', '芽', '惊', '百', '千', '如', '色', '夜', '草', 
    //   '都', '未', '见', '晚', '作', '芳', '万', '开', '答', '双', '接', '苹', '果', '巧', '克', '力', 
    //   '蛋', '糕', '客', '张', '嘴', '巴', '连', '位', '东', '西', '肚', '破', 
    //   '奔跑','休息','回答','游戏','温暖','身体','树叶','害虫','天空','夜晚',
    //   '礼物','打开','新年','草芽','白雪','梨花','树林','河马','朋友','蚂蚁'
    // ];

    // 从 sessionStorage 加载数据
    this.loadFromStorage();
    
    // 获取 DOM 元素
    this.getElements();
    
    // 绑定事件
    this.bindEvents();
    
    // 初始化显示
    this.render();
  }
  
  // 获取所有需要的 DOM 元素
  getElements() {
    this.learningSection = document.getElementById('learningSection');
    this.emptyState = document.getElementById('emptyState');
    this.wordDisplay = document.getElementById('wordDisplay');
    this.chineseWord = document.getElementById('chineseWord');
    this.pinyin = document.getElementById('pinyin');
    this.progress = document.getElementById('progress');
    this.wordList = document.getElementById('wordList');
    this.chineseInput = document.getElementById('chineseInput');
    this.addWordForm = document.getElementById('addWordForm');
    this.nextBtn = document.getElementById('nextBtn');
    this.shuffleBtn = document.getElementById('shuffleBtn');
    this.addFirstBtn = document.getElementById('addFirstBtn');
    this.prevBtn = document.getElementById('prevBtn');
    
    // 新增按钮元素
    this.loadDefaultVocab = document.getElementById('loadDefaultVocab');
    this.clearAllVocab = document.getElementById('clearAllVocab');
    
    // 音频按钮元素
    this.audioBtn = document.getElementById('audioBtn');
    
    // 颜色选择器元素
    this.colorSelector = document.getElementById('colorSelector');
    this.colorCards = document.querySelectorAll('.color-card');
    
    // 模态框相关元素
    this.pinyinModal = document.getElementById('pinyinModal');
    this.chinesePreview = document.getElementById('chinesePreview');
    this.pinyinInput = document.getElementById('pinyinInput');
    this.closeModal = document.getElementById('closeModal');
    this.cancelPinyin = document.getElementById('cancelPinyin');
    this.savePinyin = document.getElementById('savePinyin');
  }
  
  // 绑定事件监听器
  bindEvents() {
    // 添加生词表单提交事件
    this.addWordForm.addEventListener('submit', (e) => {
      e.preventDefault();
      this.addWord();
    });
    
    // 添加首个生词按钮点击事件
    this.addFirstBtn.addEventListener('click', () => {
      this.chineseInput.focus();
    });
    
    // 上一个按钮点击事件
    this.prevBtn.addEventListener('click', () => {
      this.prevWord();
    });
    
    // 下一个按钮点击事件
    this.nextBtn.addEventListener('click', () => {
      this.nextWord();
    });
    
    // 重新排序按钮点击事件
    this.shuffleBtn.addEventListener('click', () => {
      this.shuffleWords();
    });
    
    // 音频按钮点击事件
    this.audioBtn.addEventListener('click', () => {
      this.playAudio();
    });
    
    // 颜色卡片点击事件
    this.colorCards.forEach(card => {
      card.addEventListener('click', (e) => {
        this.changeWordColor(e.target);
      });
    });
    
    // 加载默认生词库按钮点击事件
    this.loadDefaultVocab.addEventListener('click', () => {
      console.info("加载默认生词库");
      this.loadDefaultVocabulary();
    });

    this.loadV20251020 = document.getElementById('v20251020');
    this.loadV20251020.addEventListener('click', () => {
      this.loadDefaultVocabulary('20251020');
    });

    this.loadV20251021 = document.getElementById('v20251021');
    this.loadV20251021.addEventListener('click', () => {
      this.loadDefaultVocabulary('20251021');
    });

    this.loadV202510hz = document.getElementById('v202510hz');
    this.loadV202510hz.addEventListener('click', () => {
      this.loadDefaultVocabulary('202510hz');
    });

    // 2025-11-03
    this.loadV20251103 = document.getElementById('v20251103');
    this.loadV20251103.addEventListener('click', () => {
      this.loadDefaultVocabulary('20251103');
    });
    
    // 清空所有生词按钮点击事件
    this.clearAllVocab.addEventListener('click', () => {
      this.clearAllVocabulary();
    });
    
    // 键盘事件监听
    document.addEventListener('keydown', (e) => {
      // 左箭头键 - 上一个
      if (e.key === 'ArrowLeft') {
        this.prevWord();
      }
      // 右箭头键 - 下一个
      else if (e.key === 'ArrowRight') {
        this.nextWord();
      }
    });
    
    // 模态框事件
    this.closeModal.addEventListener('click', () => {
      this.closePinyinModal();
    });
    
    this.cancelPinyin.addEventListener('click', () => {
      this.closePinyinModal();
    });
    
    this.savePinyin.addEventListener('click', () => {
      this.savePinyinEdit();
    });
    
    // 点击模态框外部关闭
    window.addEventListener('click', (e) => {
      if (e.target === this.pinyinModal) {
        this.closePinyinModal();
      }
    });
  }
  
  // 更改汉字颜色
  changeWordColor(selectedCard) {
    // 移除所有卡片的激活状态
    this.colorCards.forEach(card => {
      card.classList.remove('active');
    });
    
    // 添加当前卡片的激活状态
    selectedCard.classList.add('active');
    
    // 获取选中的颜色
    const color = selectedCard.getAttribute('data-color');
    
    // 应用颜色到汉字显示区域
    if (color.includes('var')) {
      // 如果是CSS变量，需要获取实际颜色值
      const computedStyle = getComputedStyle(document.documentElement);
      const colorValue = computedStyle.getPropertyValue(color.replace('var(', '').replace(')', '')).trim();
      this.chineseWord.style.color = colorValue;
    } else {
      // 直接应用颜色值
      this.chineseWord.style.color = color;
    }
  }
  
  // 播放音频功能
  playAudio() {
    if (this.words.length === 0) return;
    
    const currentWord = this.words[this.currentIndex];
    // 只有单字符词才播放音频
    if (currentWord.chinese.length === 1) {
      const pinyin = currentWord.pinyin;
      // 移除声调符号，只保留拼音字母和声调数字
      const cleanPinyin = pinyin.replace(/[^\w\s]/gi, '').replace(/\s+/g, '');
      // const audioUrl = `https://img.zdic.net/audio/zd/py/${cleanPinyin}.mp3`;
      const audioUrl = `https://img.zdic.net/audio/zd/py/${pinyin}.mp3`;
      console.log(audioUrl);
      
      // 创建音频元素并播放
      const audio = new Audio(audioUrl);
      audio.play().catch(error => {
        console.error('音频播放失败:', error);
        alert('音频播放失败，请检查网络连接或稍后重试');
      });
    }
  }
  
  // 从 sessionStorage 加载数据
  loadFromStorage() {
    const storedWords = sessionStorage.getItem('vocabularyWords');
    if (storedWords) {
      this.words = JSON.parse(storedWords);
    }
  }
  
  // 保存数据到 sessionStorage
  saveToStorage() {
    sessionStorage.setItem('vocabularyWords', JSON.stringify(this.words));
  }
  
  // 添加生词
  addWord() {
    const input = this.chineseInput.value.trim();
    
    // 验证输入
    if (!input) {
      alert('请输入汉字');
      return;
    }
    
    // 支持批量添加，用空格或逗号分隔
    const separators = /[,\s]+/; // 匹配逗号或空格
    const words = input.split(separators).filter(word => word.length > 0);
    
    let addedCount = 0;
    
    words.forEach(chinese => {
      // 验证每个词汇
      if (chinese.length > 2) {
        alert(`"${chinese}" 超过2个字符，已跳过`);
        return;
      }
      
      // 检查是否已存在
      if (this.words.some(word => word.chinese === chinese)) {
        alert(`"${chinese}" 已存在于生词库中`);
        return;
      }
      
      // 使用 pinyin-pro 库生成拼音
      const pinyinResult = pinyinPro.pinyin(chinese, { toneType: 'symbol' });
      
      // 创建生词对象
      const word = {
        id: Date.now() + addedCount, // 确保唯一ID
        chinese: chinese,
        pinyin: pinyinResult
      };
      
      // 添加到数组
      this.words.push(word);
      addedCount++;
    });
    
    // 保存到存储
    this.saveToStorage();
    
    // 清空输入框
    this.chineseInput.value = '';
    
    // 重新渲染
    this.render();
    
    // 提示添加结果
    if (addedCount > 0) {
      alert(`成功添加 ${addedCount} 个生词`);
    }
  }
  
  // 加载默认生词库
  loadDefaultVocabulary(key) {
    console.info("key:" + key);

    if (this.words.length > 0) {
      const confirmLoad = confirm('加载默认生词库将会保留现有生词并添加新词，是否继续？');
      if (!confirmLoad) return;
    }
    
    let addedCount = 0;
    let list = [];
    if(!key) {
      key='all';
    }
    list = this.vocabularyMap.get(key);

    // this.defaultVocabulary.forEach((chinese, index) => {
    list.forEach((chinese, index) => {
      // 检查是否已存在
      if (this.words.some(word => word.chinese === chinese)) {
        return; // 已存在，跳过
      }
      
      // 使用 pinyin-pro 库生成拼音
      const pinyinResult = pinyinPro.pinyin(chinese, { toneType: 'symbol' });
      
      // 创建生词对象
      const word = {
        id: Date.now() + index, // 确保唯一ID
        chinese: chinese,
        pinyin: pinyinResult
      };
      
      // 添加到数组
      this.words.push(word);
      addedCount++;
    });
    
    // 保存到存储
    this.saveToStorage();
    
    // 重新渲染
    this.render();
    
    // 提示添加结果
    alert(`成功添加 ${addedCount} 个默认生词`);
  }
  
  // 清空所有生词
  clearAllVocabulary() {
    if (this.words.length === 0) {
      alert('当前没有生词可清空');
      return;
    }
    
    const confirmClear = confirm('确定要清空所有生词吗？此操作不可恢复。');
    if (!confirmClear) return;
    
    this.words = [];
    this.currentIndex = 0;
    
    // 保存到存储
    this.saveToStorage();
    
    // 重新渲染
    this.render();
    
    alert('已清空所有生词');
  }
  
  // 删除生词
  deleteWord(id) {
    this.words = this.words.filter(word => word.id !== id);
    this.saveToStorage();
    
    // 如果当前索引超出范围，调整索引
    if (this.currentIndex >= this.words.length && this.words.length > 0) {
      this.currentIndex = this.words.length - 1;
    }
    
    this.render();
  }
  
  // 打开拼音编辑模态框
  openPinyinModal(id) {
    const word = this.words.find(w => w.id === id);
    if (!word) return;
    
    this.currentEditId = id;
    this.chinesePreview.textContent = word.chinese;
    this.pinyinInput.value = word.pinyin;
    this.pinyinModal.style.display = 'block';
    this.pinyinInput.focus();
  }
  
  // 关闭拼音编辑模态框
  closePinyinModal() {
    this.pinyinModal.style.display = 'none';
    this.currentEditId = null;
  }
  
  // 保存拼音编辑
  savePinyinEdit() {
    if (!this.currentEditId) return;
    
    const newPinyin = this.pinyinInput.value.trim();
    if (!newPinyin) {
      alert('请输入拼音');
      return;
    }
    
    // 更新词汇的拼音
    const wordIndex = this.words.findIndex(w => w.id === this.currentEditId);
    if (wordIndex !== -1) {
      this.words[wordIndex].pinyin = newPinyin;
      this.saveToStorage();
      this.render();
      
      // 如果当前显示的就是这个词汇，更新学习区域
      if (this.currentIndex === wordIndex) {
        this.updateWordDisplay();
      }
    }
    
    this.closePinyinModal();
  }
  
  // 上一个生词
  prevWord() {
    if (this.words.length === 0) return;
    
    this.currentIndex = (this.currentIndex - 1 + this.words.length) % this.words.length;
    this.updateWordDisplay();
  }
  
  // 下一个生词
  nextWord() {
    if (this.words.length === 0) return;
    
    this.currentIndex = (this.currentIndex + 1) % this.words.length;
    this.updateWordDisplay();
  }
  
  // 重新排序生词
  shuffleWords() {
    if (this.words.length <= 1) return;
    
    // Fisher-Yates 洗牌算法
    for (let i = this.words.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [this.words[i], this.words[j]] = [this.words[j], this.words[i]];
    }
    
    this.currentIndex = 0;
    this.saveToStorage();
    this.render();
  }
  
  // 更新生词显示
  updateWordDisplay() {
    if (this.words.length === 0) return;
    
    const currentWord = this.words[this.currentIndex];
    this.chineseWord.textContent = currentWord.chinese;
    this.pinyin.textContent = currentWord.pinyin;
    this.progress.textContent = `${this.currentIndex + 1}/${this.words.length}`;
    
    // 只有单字符词才显示音频按钮
    if (currentWord.chinese.length === 1) {
      this.audioBtn.style.display = 'block';
    } else {
      this.audioBtn.style.display = 'none';
    }
    
    // 保持当前选中的颜色
    const activeCard = document.querySelector('.color-card.active');
    if (activeCard) {
      this.changeWordColor(activeCard);
    }
  }
  
  // 渲染生词列表
  renderWordList() {
    this.wordList.innerHTML = '';
    
    this.words.forEach((word, index) => {
      const wordCard = document.createElement('div');
      wordCard.className = 'word-card';
      wordCard.innerHTML = `
        <div class="word-card-content">
          <div class="word-card-chinese">${word.chinese}</div>
          <div class="word-card-pinyin">${word.pinyin}</div>
        </div>
        <div class="word-card-actions">
          <button class="edit-pinyin-btn" data-id="${word.id}">编辑拼音</button>
          <button class="delete-btn" data-id="${word.id}">删除</button>
        </div>
      `;
      
      this.wordList.appendChild(wordCard);
    });
    
    // 绑定编辑拼音按钮事件
    document.querySelectorAll('.edit-pinyin-btn').forEach(button => {
      button.addEventListener('click', (e) => {
        const id = parseInt(e.target.getAttribute('data-id'));
        this.openPinyinModal(id);
      });
    });
    
    // 绑定删除按钮事件
    document.querySelectorAll('.delete-btn').forEach(button => {
      button.addEventListener('click', (e) => {
        const id = parseInt(e.target.getAttribute('data-id'));
        this.deleteWord(id);
      });
    });
  }
  
  // 渲染主界面
  render() {
    // 根据是否有生词显示不同界面
    if (this.words.length > 0) {
      this.learningSection.style.display = 'block';
      this.emptyState.style.display = 'none';
      
      // 更新显示
      this.updateWordDisplay();
    } else {
      this.learningSection.style.display = 'none';
      this.emptyState.style.display = 'block';
      
      // 重置索引
      this.currentIndex = 0;
    }
    
    // 渲染生词列表
    this.renderWordList();
  }
}

// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', () => {
  // 检查是否引入了 pinyin-pro 库
  if (typeof pinyinPro === 'undefined') {
    console.error('pinyin-pro library not loaded');
    return;
  }
  
  // 初始化应用
  new VocabularyApp();
});